1157F - Maximum Balanced Circle - CodeForces Solution


constructive algorithms dp greedy two pointers *2000

Please click on ads to support us..

C++ Code:

/*
Problem: 1157F
Date: 16-01-2024 05:00 AM
*/


#include <iostream>
#include <algorithm>
#include <set>

using namespace std;

int n;
int a[200000];
multiset<int> s;

int main() {
	cin >> n;
	for(int i = 0; i < n; i++) {
		cin >> a[i];
	}
	sort(a, a + n);
	int l = 0;
	int maxlen = 1;
	int maxidx = 0;
	for(int i = 1; i < n; i++) {
		if(a[i] > a[i - 1] + 1) {
			if(i - l > maxlen) {
				maxlen = i - l;
				maxidx = l;
			}
			l = i;
		}else if(a[i] == a[i - 1] + 1) {
			int j = 0;
			for(j = 0; i + j < n && a[i + j] == a[i]; j++);
			if(j == 1) {
				if(i + j - l > maxlen) {
					maxlen = i + j - l;
					maxidx = l;
				}
				l = i + j - 1;
			}
			i = i + j - 1;
		}
	}
	if(n - l > maxlen) {
		maxlen = n - l;
		maxidx = l;
	}
	cout << maxlen << endl;

	int mymin = a[maxidx];
	int mymax = a[maxidx + maxlen - 1];
	for(int i = 0; i < maxlen; i++) {
		s.insert(a[maxidx + i]);
	}
	for(int i = mymax; i > mymin; i--) {
		cout << i << " ";
		s.erase(s.find(i));
	}
	while(!s.empty()) {
		cout << *s.begin() << " ";
		s.erase(s.begin());
	}
}


Comments

Submit
0 Comments
More Questions

1691B - Shoe Shuffling
1706A - Another String Minimization Problem
1695B - Circle Game
1702B - Polycarp Writes a String from Memory
1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String
1708B - Difference of GCDs
863A - Quasi-palindrome
1478A - Nezzar and Colorful Balls
1581B - Diameter of Graph
404A - Valera and X
908A - New Year and Counting Cards
146A - Lucky Ticket
1594C - Make Them Equal
1676A - Lucky
1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA